<?php

namespace GuanChanghu\Exception;

use GuanChanghu\Configs\FieldConfig;
use Exception;
use JetBrains\PhpStorm\Pure;
use Throwable;

/**
 * Class LogException
 * @package GuanChanghu\Exception
 */
class LogException extends Exception
{
    /**
     * 错误码
     */
    public const CODE = 400;

    /**
     * 错误码
     */
    protected $code = self::CODE;

    /**
     * LogException constructor.
     * @param string $message
     * @param int $code
     */
    #[Pure] public function __construct(string $message, int $code = 0)
    {
        parent::__construct($message, $code ?: static::CODE);
    }

    /**
     * @param Throwable $throwable
     * @param int $tierNum
     * @return array
     */
    public static function getCallingMethodPath(Throwable $throwable, int $tierNum = 5): array
    {
        $traceMany = $throwable->getTrace();

        $list = [
            'code' => $throwable->getCode(), FieldConfig::MESSAGE_FIELD => $throwable->getMessage()
        ];

        foreach ($traceMany as $tier => $trace) {
            if ($tier > $tierNum) {
                break;
            }

            $list[] = [
                'path' => isset($trace['file']) ? ($trace['file'] . ':' . $trace['line']) : '',
                'method' => isset($trace['class']) ? ($trace['class'] . $trace['type'] . $trace['function']) : '',
            ];
        }

        return $list;
    }
}
